import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}

object SparkStreaming_1 {
  def main(args: Array[String]): Unit = {
    // 配置 Spark
    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount")

    // 创建 StreamingContext，每 5 秒统计一次
    val ssc = new StreamingContext(sparkConf, Seconds(5))

    // 从网络套接字接收数据
    val dStream: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)

    // 数据处理：词频统计
    val lines: DStream[String] = dStream.flatMap(_.split(" "))
    val wordDStream: DStream[(String, Int)] = lines.map((_, 1))
    val result: DStream[(String, Int)] = wordDStream.reduceByKey(_ + _)

    // 数据保存：打印结果
    result.print()

    // 启动 StreamingContext
    ssc.start()

    // 等待终止
    ssc.awaitTermination()
  }
}